﻿using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;

namespace DeHeng_Mes.Model.OrderSingleton
{
    public sealed class OrderSingleton
    {
        // 静态只读实例，在静态构造函数中初始化（饿汉式）
        private static readonly List<OrderSingletonModel> _instance;

        private static readonly object _lock = new object();

        // 静态构造函数：类加载时自动调用，保证线程安全
        static OrderSingleton()
        {
            _instance = new List<OrderSingletonModel>();
        }

        // 私有构造函数防止外部实例化
        private OrderSingleton()
        {

        }

        // 全局访问点（属性形式更符合 C# 习惯）
        public static List<OrderSingletonModel> Instance => _instance;

        // 线程安全的删除方法
        public static void RemoveByOrderId(string wo_code)
        {
            lock (_lock)
            {
                _instance.RemoveAll(order => order.OrderId.Equals(wo_code));

                Tools.ProduceLogText($"工单结束，移除[{wo_code}]");
            }
        }

        public static void AddOrder(OrderSingletonModel order)
        {
            lock (_lock)
            {
                OrderSingletonModel orderSingletonModel = Instance.Where(x => x.OrderId.Equals(order.OrderId) && x.PlcName.Equals(order.PlcName) && x.MaterialId.Equals(order.MaterialId)).FirstOrDefault();

                if (orderSingletonModel == null)
                    _instance.Add(order);
            }
        }

        public static void AddBatch(string wo_code, string batch, string st)
        {
            lock (_lock)
            {
                foreach (var item in _instance)
                {
                    if (item.OrderId.Equals(wo_code))
                    {
                        item.Batch[st] = batch;
                    }
                }
            }
        }

        public static int GetCount()
        {
            List<string> strings = new List<string>();

            lock (_lock)
            {
                foreach (var item in _instance)
                {
                    if (!strings.Contains(item.OrderId))
                    {
                        strings.Add(item.OrderId);
                    }
                }
            }

            return strings.Count;
        }

        /// <summary>
        /// 更新工单状态
        /// </summary>
        /// <param name="wo_code"></param>
        /// <param name="wo_status"></param>
        /// <exception cref="NotImplementedException"></exception>
        public static void UpDateStatus(string wo_code, string wo_status)
        {
            lock (_lock)
            {
                foreach (var item in _instance)
                {
                    if (item.OrderId.Equals(wo_code))
                    {
                        item.Status = wo_status;
                    }
                }
            }
        }

        /// <summary>
        /// 更新数量
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="plcName"></param>
        /// <param name="num"></param>
        public static void AddNumNow(string orderId)
        {
            lock (_lock)
            {
                foreach (var item in _instance)
                {
                    if (item.OrderId.Equals(orderId))
                    {
                        item.ProducessNumNow = item.ProducessNumNow + 1;

                        Tools.ProduceLogText($"[{orderId}]实时产量为[{item.ProducessNumNow}]");
                    }
                }
            }
        }

        /// <summary>
        /// 返回当前工位的工单
        /// </summary>
        /// <param name="v1"></param>
        /// <param name="v2"></param>
        /// <returns></returns>
        public static OrderSingletonModel GetOrderId(string station)
        {
            // 获取当前工位对应的物料编码
            string materialId = MappingTable.GetMaterialByStation(station);

            if (string.IsNullOrEmpty(materialId))
                return null;

            OrderSingletonModel orderSingletonModel = _instance.Where(x => x.MaterialId.Equals(materialId)).FirstOrDefault();

            if (orderSingletonModel == null)
                return null;

            return orderSingletonModel;
        }

        /// <summary>
        /// 更新计划数量
        /// </summary>
        /// <param name="plan_num"></param>
        public static void UpdateProductionNum(string wo_code, int plan_num)
        {
            lock (_lock)
            {
                foreach (var item in _instance)
                {
                    if (item.OrderId.Equals(wo_code))
                    {
                        item.ProducessNum = plan_num;

                        Tools.ProduceLogText($"{wo_code}计划产量更新为[{plan_num}]");
                    }
                }
            }
        }
    }
}
